package com.apes.framework.plugin.esb.parser.element;


import com.apes.framework.plugin.esb.processor.ChainProcessor;
import com.apes.framework.plugin.esb.processor.jpa.FilterProcessor;
import com.apes.framework.plugin.filereader.xml.ApesElement;
import com.apes.framework.util.MapUtil;
import com.apes.framework.util.Operation;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 功能：
 *
 * @author xul
 * @create 2018-12-03 11:50
 */
@Component
public class FilterElementParser extends AbstractProcessorParser {
    /**
     * 可解析的元素列表
     **/
    private final String[] elementNames = {"filter"};

    /**
     * 功能：可解析的元素列表
     */
    @Override
    public String[] getNames() {
        return elementNames;
    }


    @Override
    <T extends Class> T getChainProcessorClass() {
        return (T) FilterProcessor.class;
    }

    @Override
    public ChainProcessor parse(ApesElement element) {
        List<Map<String, Object>> filters = new ArrayList<>();
        element.getNestedElements().stream().forEach(nestedElement -> {
            FilterProcessor processor = nestedElement.parse();
            filters.addAll(processor.getFilters());
        });

        String field = element.getAttribute("field"); //字段
        String operator = element.getAttribute("operator"); //操作
        if (StringUtils.isEmpty(operator)) operator = "=";
        String searchType = Operation.getSearchType(operator.trim());
        if (searchType != null) operator = searchType;
        String value = element.getAttribute("value"); //值
        String type = element.getAttribute("type"); // 类型
        if (isNotEmpty(field) && isNotEmpty(value)) {
            filters.add(MapUtil.mapper("field", field, "operator", operator, "value", getValue(value), "type", type));
        }

        FilterProcessor processor = new FilterProcessor();
        processor.setFilters(filters);
        return processor;
    }

    private Object getValue(String value){
        if(value.toLowerCase().equals("true") || value.toLowerCase().equals("false")) return Boolean.valueOf(value);
        if ("null".equals(value.toLowerCase())) return  null;
        return value;
    }

    private boolean isNotEmpty(@Nullable Object str) {
        return !StringUtils.isEmpty(str);
    }
}
